<template>
  <div>
    <TopBar ref="topBar" :tabName="tabName" :backValue="backValue">
      <template #operate>
        <!-- <el-button :loading="loading" @click="cancel">取消</el-button> -->
        <el-button :loading="loading" type="primary" @click="save">保存</el-button>
      </template>
    </TopBar>
    <div class="myFormBox" v-loading="loading">
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="发放名称" prop="releaseName" :rules="getRules('input', '发放名称')">
          <el-input style="width: 360px;" v-model="form.releaseName" :maxlength="20" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input style="width: 360px;" v-model="form.remarks" :maxlength="20" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="发放类型" prop="releaseType" :rules="getRules('input', '发放类型')">
          <el-radio-group v-model="form.releaseType">
            <el-radio :label="0">自动发放</el-radio>
            <el-radio :label="1">主动领取</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发放对象" prop="releaseObject" :rules="getRules('input', '发放对象')">
          <el-radio-group v-model="form.releaseObject">
            <el-radio :label="0">全部门店</el-radio>
            <el-radio :label="1">指定门店</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.releaseObject" label="指定门店" prop="designatedStore" :rules="designatedStoreRules">
          <div style="width: 100%;">
            <div style="margin-bottom: 8px;">
              <el-button @click="designatedStoreDialogOpen" type="primary" text>选择</el-button>
            </div>
            <el-table :header-cell-style="{ background: '#ddd' }" stripe :data="listData" max-height="200"
              style="width: 420px;">
              <el-table-column show-overflow-tooltip width="324" prop="storeName" label="门店名称"></el-table-column>
              <el-table-column label="操作" width="96">
                <template v-slot="{ row, $index }">
                  <el-button type="danger" plain @click="delStore(row, $index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="myPagination">
              <el-pagination v-model:current-page="pageConfig.page" v-model:page-size="pageConfig.pageSize"
                :page-sizes="pageConfig.pageSizes" :layout="pageConfig.layout" :total="total" background
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="发放时间" prop="releaseTime" :rules="getRules('input', '发放时间')">
          <el-radio-group v-model="form.releaseTime">
            <el-radio :label="0">立即发放</el-radio>
            <el-radio :label="1">
              <el-form-item class="flex align-items-center" style="margin-bottom:0px" prop="releaseTimeValue"
                :rules="form.releaseTime ? releaseTimeValueRules : []">
                <span style="margin-right:12px">指定时间</span>
                <el-date-picker v-model="form.releaseTimeValue" type="datetimerange" start-placeholder="开始时间"
                  end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                  date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
              </el-form-item>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="弹窗展示" prop="releaseDialog" :rules="getRules('input', '弹窗展示')">
          <div>
            <div>
              <el-radio-group v-model="form.releaseDialog">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </div>
            <div class="tips">
              若选择【是】，用户在进入采购商城首页会弹窗展示本次发放的优惠券
            </div>
          </div>
        </el-form-item>
        <el-form-item label="发放内容" prop="releaseContent" :rules="releaseContentRules">
          <div style="width: 100%;">
            <div class="flex align-items-center justify-content-between" style="margin-bottom:10px">
              <div class="flex align-items-center">
                <el-button style="margin-right: 16px;" type="primary" plain @click="couponSelectDialogOpen">
                  <img class="btn-icon" :src="addIcon" alt="">
                  选择
                </el-button>
                <span class="tips">最多选择3种，每种最多发放2张</span>
              </div>
              <el-button v-show="form.releaseType" type="primary" plain round @click="handleBulkFilling">批量填充</el-button>
            </div>
            <!-- 自动领取 -->
            <el-table v-if="!form.releaseType" :header-cell-style="{ background: '#ddd' }" stripe :data="releaseContent"
              max-height="300" style="width: 100%;">
              <el-table-column min-width="256" show-overflow-tooltip prop="couponName" label="优惠劵名称"></el-table-column>
              <el-table-column min-width="230" label="赠券数">
                <template #header>
                  <div class="flex align-items-center">
                    <span>赠券数</span>
                    <el-tooltip content="赠券数:单个发卷对象发放数量" placement="top-start">
                      <img :src="warningCircle" class="warningCircleIcon" />
                    </el-tooltip>
                  </div>
                </template>
                <template v-slot="{ row }">
                  <el-input style="width:120px" v-model="row.couponNum" @input="()=>{row.couponNum=limitInt(row.couponNum)}"
                    placeholder="请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column min-width="230" prop="surplusQuantity" label="剩余数量"></el-table-column>
              <el-table-column min-width="230" prop="promotionalContent" label="优惠内容">
                <template v-slot="{ row }">
                  <div class="flex align-items-center">
                    <span>{{ row.promotionalContent }}</span>
                    <el-tooltip content="Top Left prompts info" placement="top-start">
                      <img class="warningCircleIcon" :src="warningCircle" alt="">
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template v-slot="{ row, $index }">
                  <el-button type="danger" plain @click="delItem(row, $index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 主动领取 -->
            <el-table v-else :header-cell-style="{ background: '#ddd' }" stripe :data="form.releaseContent"
              max-height="300" style="width: 100%;">
              <el-table-column min-width="256" show-overflow-tooltip prop="couponName" label="优惠劵名称"></el-table-column>
              <el-table-column min-width="150" label="是否限制次数">
                <template v-slot="{ row }">
                  <el-switch v-model="row.limitingFrequency" />
                </template>
              </el-table-column>
              <el-table-column min-width="164" prop="surplusQuantity" label="每人每天限领">
                <template #header>
                  <el-input :model-value="bulkFillingForm.dailyLimit"
                    @input="(val) => inputLimit(val, bulkFillingForm, 'dailyLimit')" placeholder="每人每天限领"></el-input>
                </template>
                <template v-slot="{ row, $index }">
                  <el-form-item label="" v-if="row.limitingFrequency" :prop="'releaseContent.' + $index + '.dailyLimit'"
                    :rules="getRules('input', '')">
                    <el-input v-model="row.dailyLimit" @input="()=>{row.dailyLimit=limitInt(row.dailyLimit)}" placeholder="请输入"></el-input>
                  </el-form-item>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column min-width="164" prop="promotionalContent" label="发放时间限领">
                <template #header="{ row }">
                  <el-input :model-value="bulkFillingForm.timeLimitCollar"
                    @input="(val) => inputLimit(val, bulkFillingForm, 'timeLimitCollar')" placeholder="发放时间限领"></el-input>
                </template>
                <template v-slot="{ row, $index }">
                  <el-form-item v-if="row.limitingFrequency" :prop="'releaseContent.' + $index + '.timeLimitCollar'"
                    :rules="getRules('input', '')">
                    <el-input v-model.number="row.timeLimitCollar" @input="()=>{row.timeLimitCollar=limitInt(row.timeLimitCollar)}"
                      placeholder="请输入"></el-input>
                  </el-form-item>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column min-width="88" prop="surplusQuantity" label="剩余数量"></el-table-column>
              <el-table-column min-width="115" prop="promotionalContent" label="优惠内容">
                <template v-slot="{ row }">
                  <div class="flex align-items-center">
                    <span>{{ row.promotionalContent }}</span>
                    <el-tooltip content="Top Left prompts info" placement="top-start">
                      <img class="warningCircleIcon" :src="warningCircle" alt="">
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template v-slot="{ row, $index }">
                  <el-button type="danger" plain @click="delItem(row, $index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <StoreSelectDialog :show="designatedStoreDialogShow" @close="designatedStoreDialogClose" />
    <CouponSelectDialog :show="couponSelectDialogShow" @close="couponSelectDialogClose" />
  </div>
</template>

<script setup>
import { useTableData } from '../Hooks/index';
import { useIssueAction } from '../Hooks/issueAction.js'
import { useConfirm, useManualPaging,useImportImg } from '@/hooks/index.js'
import TopBar from '@/components/Topbar/index.vue';
import warningCircle from '@/assets/icon/warning-circle.png'
import getRules from '@/validUtils';
import StoreSelectDialog from '../Components/StoreSelectDialog.vue'
import CouponSelectDialog from '../Components/CouponSelectDialog.vue'
import { limitInt } from '@/utils/common.js'
const addIcon = useImportImg('btn-add-blue')
const { issueSearchTable } = useTableData();
const route = useRoute();
const isEdit = computed(() => route.query.id ? true : false)
const tabName = computed(() => isEdit.value ? '编辑发放' : '新增发放')
const topBar = ref();
const backValue = '/wholesaleManagement/marketingManagement/couponManagement/couponManagementIndex'
const loading = ref(false)



const formRef = ref(null)
const form = ref({
  releaseName: '',
  remarks: '',
  releaseType: 0,
  releaseObject: 0,
  releaseTime: 0,
  releaseTimeValue: '',
  releaseDialog: 1,
  releaseContent: [],
  designatedStore: []
})
const { releaseContent, designatedStore } = useIssueAction()
const {
  pageConfig,
  listData,
  total,
  handleSizeChange,
  handleCurrentChange } = useManualPaging(designatedStore, { layout: 'prev, pager, next' })

watch(releaseContent, (newVal) => {
  if (newVal.length) {
    form.value.releaseContent = newVal
  }
})
const releaseContentRules = [{
  required: true,
  validator: (rule, value, callback) => {
    if (releaseContent.value.length === 0) {
      callback(new Error('请选择发放内容'))
    } else {
      callback()
    }
  },
  trigger: 'change'
}]
const designatedStoreRules = [{
  required: true,
  validator: (rule, value, callback) => {
    if (form.value.releaseObject && designatedStore.value.length === 0) {
      callback(new Error('请选择指定门店'))
    } else {
      callback()
    }
  },
  trigger: 'change'
}]
const releaseTimeValueRules = [{
  validator: (rule, value, callback) => {
    if (form.value.releaseTime && !form.value.releaseTimeValue) {
      callback(new Error('请选择发放时间'))
      console.log('1', 1)
    } else {
      callback()
    }
  },
  trigger: 'blur'
}]
const designatedStoreDialogShow = ref(false)
const designatedStoreDialogClose = (data) => {
  designatedStoreDialogShow.value = false
}
const designatedStoreDialogOpen = () => {
  designatedStoreDialogShow.value = true
}
const delStore = (row, index) => {
  designatedStore.value.splice(index, 1)
}

const couponSelectDialogShow = ref(false)
const couponSelectDialogClose = (data) => {
  couponSelectDialogShow.value = false
}
const couponSelectDialogOpen = () => {
  couponSelectDialogShow.value = true
}
const delItem = (row, index) => {
  ElMessageBox.confirm('确定删除该优惠劵吗？', '提示', {
    type: 'warning',
    beforeClose: async (action, instance, done) => {
      const func = async () => {
        releaseContent.value.splice(index, 1)
        return true
      }
      const confirm = await useConfirm(action, instance, done, func,)
      if (confirm) {
        ElMessage.success('删除成功')
      }
    }
  })
}

const bulkFillingForm = ref({
  dailyLimit: null,
  timeLimitCollar: null,
})

const handleBulkFilling = () => {
  if(form.value.releaseContent.length){
    form.value.releaseContent.forEach((item, index) => {
      item.dailyLimit = bulkFillingForm.value.dailyLimit
      item.timeLimitCollar = bulkFillingForm.value.timeLimitCollar
    })
  }
}

const inputLimit = (val, data, key, limitSize = 9) => {
  val = val.replace(/\D/g, "");
  if (val.length > limitSize) {
    data[key] = val.slice(0, limitSize)
    return
  }
  data[key] = val
}

const save = () => {
  console.log('bulkFillingForm', bulkFillingForm.value)
  formRef.value.validate((valid) => {
    if (valid) {
      console.log(form.value)
      formRef.value.resetFields()
      form.value = {
        releaseName: '',
        remarks: '',
        releaseType: 0,
        releaseObject: 0,
        releaseTime: 0,
        releaseDialog: 1,
        releaseContent: []
      }
      issueSearchTable.value && issueSearchTable.value.handlerSearch()
      cancel()
    }
  })
}
const cancel = () => {
  topBar.value.backHandle()
}
onActivated(() => {
  if (isEdit.value) {
    loading.value = true
    setTimeout(() => {
      loading.value = false
    }, 1000)
  } else {

  }
})
</script>

<style lang="less" scoped>
.myFormBox {
  padding: 24px;
}

.tips {
  width: 100%;
  color: #666;
  font-size: 12px;
}

.myPagination {
  width: 420px;
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.btn-icon {
  width: 14px;
  height: 14px;
  margin-right: 4px;
}
</style>